package com.swlz.servlet.user;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.swlz.Const;
import com.swlz.entity.User;
import com.swlz.service.UserService;
import com.swlz.service.WebFileService;
import com.swlz.service.impl.UserServiceImpl;
import com.swlz.service.impl.WebFileServiceForGoFastDFS;

import cn.hutool.core.io.FileUtil;


@WebServlet("/user/header-upload.let")
@MultipartConfig(
		maxFileSize = -1,
		maxRequestSize = -1
)
public class HeaderUploadServlet extends HttpServlet {
       

	protected Logger log = LoggerFactory.getLogger(this.getClass());
	private UserService userService = new UserServiceImpl();

	private WebFileService webFileService = new WebFileServiceForGoFastDFS();
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User u = new User();
		log.debug("文件上传开始");
		Long id = null;
		try {
			id = Long.valueOf(Const.getLoginUser(request.getSession()).getUserId());
		} catch (Exception e) {
			throw new RuntimeException("获取参数失败");
		}
		Map<String,Object> ret = new HashMap<String, Object>();
		try {
			
			File root = new File(getServletContext().getRealPath("/"));
			log.debug("获取网站的根目录：{}",root);
			
			String uri = "front/images/";
			new File(root,uri).mkdirs();
			log.debug("创建保存文件的目录：{}",uri);
			
			
			Part img = request.getPart("HeaderImgs");//获取上传的文件
			
			String ext = FileUtil.extName(img.getSubmittedFileName());
			log.debug("获取上传文件的扩展名：{}",ext);
			
			uri += UUID.randomUUID()+"."+ext;
			log.debug("保存的文件：{}",uri);
			
			u.setUserImg(uri);
			log.debug("具体保存的文件：{}",new File(root,uri));
			img.write(new File(root,uri).toString());
			
			ret.put("ok", true);
			ret.put("uri",uri);
		}catch (Exception e) {
			log.warn("文件上传失败",e);
			ret.put("ok", false);
			ret.put("message", e.getMessage());
		}
		
		response.reset();
		response.setContentType("text/json;charset=UTF-8");
		response.getWriter().print(JSON.toJSONString(ret));
		response.flushBuffer();
		log.debug("文件上传结束");
		u.setUserId(id);
		log.debug(u.toString());
		
		userService.update(u);
	}

}
